const axios = require('axios');
const BaseIpcHandler = require('../BaseIpcHandler');

class CondaEnvServerHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log(`>> CondaEnvServerHandler params = `, params);
        const { method, envPath } = params;

        // 业务逻辑
        let result = null;
        try {
            if (method === 'list') {
                // 获取conda环境列表
                try {
                    const listUrl = 'https://label-anything.bd.bcebos.com/labelapp/conda/index.json';
                    const response = await axios.get(listUrl);
                    // console.log(response);
                    result = { code: 0, msg: response.data };
                } catch (error) {
                    result = { code: -1, msg: error.message };
                }
            } else if (method === 'get' && envPath) {
                // 获取conda环境安装脚本
                try {
                    const scriptUrl = `https://label-anything.bd.bcebos.com/labelapp/conda/${envPath}.txt`;
                    const response = await axios.get(scriptUrl);
                    const envScript = response.data.trim();
                    result = { code: 0, msg: envScript };
                } catch (error) {
                    result = { code: -1, msg: error.message };
                }
            } else {
                result = { code: -1, msg: 'Invalid request params' };
            }
        } catch (err) {
            console.error(`Get remote conda list Failed!, Error =`, err);
            result = { code: -1, msg: err.msg };
        }

        // 返回结果
        // console.log(`CondaEnvServerHandler result = `, result);
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = CondaEnvServerHandler;
